package com.tree.thread.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import static java.lang.Thread.sleep;

/**
 * @ClassName com.tree.thread.aqs
 * Description: <类功能描述>. <br>
 * <p>
 * 参考ReentrantLock自己实现锁
 * </p>
 * @Author tree
 * @Date 2019-12-13 22:17
 * @Version 1.0
 */
public class SelfLock implements Lock {

    /**
    state=1表示获取到锁， state=0表示这个锁当前线程没有拿到
     */
    private static class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }


        @Override
        protected boolean tryAcquire(int arg) {
            //在设置state的时候使用CAS方法， state 由0 设置为1，代表获取到锁
            if(compareAndSetState(0,1)){
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }

            return false;
        }

        /**
         * 独占锁，在释放锁的时候使用，因为只有当前线程拥有锁，不需要用原子cas设置(compareAndSetState)，不会有并发问题
         * @param arg
         * @return
         */
        @Override
        protected boolean tryRelease(int arg) {
            if(getState() == 0){
                throw new UnsupportedOperationException();
            }
            setExclusiveOwnerThread(null);
            //在释放锁的时候不需要， 因为是独占锁，只有当前线程拥有锁
            setState(0);
            return true;
        }

        Condition newCondition(){
            return new ConditionObject();
        }
    }

    private final Sync sync = new Sync();

    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1,unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.release(1);

    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}


class  TestMyLock{
    public void test() throws InterruptedException {
        final Lock lock = new SelfLock();
        class Worker extends Thread{
            @Override
            public void run() {
                while (true){
                    lock.lock();
                    try{
                        try {
                            sleep(1000);
                            System.out.println(Thread.currentThread().getName());
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }finally {
                        lock.unlock();
                    }
                    try {
                        sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }



        for (int i = 0; i < 10; i++) {
            Worker w = new Worker();
            w.setDaemon(true);
            w.start();

        }

        //主线程每隔1s换行
        for (int i = 0; i< 10; i++){
            sleep(1000);
            System.out.println();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestMyLock myLock = new TestMyLock();
        myLock.test();
    }
}